package com.dqp.cslggroup.School;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.dqp.cslggroup.ConnectSever.Accept;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.bean.Talk;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.TalkAdapter;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Objects;

@SuppressLint("Registered")
public class CampusTalk extends BaseActivity implements AbsListView.OnScrollListener {
    private ArrayList<Talk> dataList;
    private Context context = CampusTalk.this;
    private TalkAdapter talkAdapter;
    private View loadmoreView;
    private LayoutInflater inflater;
    private ListView listView;
    private int last_index;
    private int first_index;
    private int total_index;
    private boolean isLoading = false, showMore = true;//表示是否正处于加载状态
    private int count = 1, sum = 0;
    private LinearLayout head;

    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.club);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        inflater = LayoutInflater.from(this);
        loadmoreView = inflater.inflate(R.layout.bottom, null);//获得刷新视图
        loadmoreView.setVisibility(View.GONE);//设置刷新视图默认情况下是不可见的
        listView = findViewById(R.id.club_list);
        listView.setOnScrollListener(this);
        listView.addFooterView(loadmoreView, null, false);
        head = findViewById(R.id.list_head);
        talkAdd();
        if (NetCheckUtil.checkNet(context)) {
            initList();
        } else {
            ToastUtil.showToast("请连接网络！");
            head.setVisibility(View.GONE);
        }
    }

    public void talkAdd() {
        TextView add = findViewById(R.id.seting);
        add.setText(getResources().getString(R.string.icon_add));
        add.setVisibility(View.VISIBLE);
        add.setOnClickListener(v -> {
            Intent intent = new Intent(context, Talk_submit.class);
            startActivityForResult(intent, 1);
        });
    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initList() {
        new Thread(() -> {
            ArrayList<Talk> dataList = Accept.getTalk(count);
            if (dataList!=null && dataList.size() > 0)
                sum = dataList.get(0).getSum() / 5;
            EventBus.getDefault().post(new MessageEvent("CampusTalk", 1, dataList));
        }).start();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            count = 1;
            initList();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        last_index = firstVisibleItem + visibleItemCount;
        first_index = firstVisibleItem;
        total_index = totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (last_index == total_index && (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE)) //表示此时需要显示刷新视图界面进行新数据的加载(要等滑动停止)
        {
            if (!isLoading && showMore) {
                isLoading = true;  //不处于加载状态的话对其进行加载
                loadmoreView.setVisibility(View.VISIBLE);    //设置刷新界面可见
                onLoad();
            }
        }
    }

    /**
     * 刷新加载
     */
    public void onLoad() {
        if (count < sum) {
            // 加载完毕
            count++;
            new Thread(() -> {
                ArrayList<Talk> addDataList = Accept.getTalk(count);
                if (addDataList.size() == 0) {
                    showMore = false;
                } else dataList.addAll(addDataList);
                EventBus.getDefault().post(new MessageEvent("CampusTalk", 2, null));
            }).start();
        }
    }

    /**
     * 加载完成
     */
    public void loadComplete() {
        loadmoreView.setVisibility(View.GONE);//设置刷新界面不可见
        isLoading = false;//设置正在刷新标志位false
        CampusTalk.this.invalidateOptionsMenu();
        listView.removeFooterView(loadmoreView);//如果是最后一页的话，则将其从ListView中移出
    }

    /**
     * 加载完成
     */
    public void showBottom_line() {
        if (!showMore) {
            View bottom_line = inflater.inflate(R.layout.bottom_line, null);//获得刷新视图
            bottom_line.setVisibility(View.VISIBLE);//设置刷新视图默认情况下是不可见的
            listView.addFooterView(bottom_line);
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("CampusTalk")) {
            switch (event.getWhat()) {
                case 1:
                    dataList = (ArrayList<Talk>) event.getObj();
                    talkAdapter = new TalkAdapter(dataList, CampusTalk.this);
                    listView.setAdapter(talkAdapter);
                    listView.setOnItemClickListener((adapterView, view, i, l) -> {
                        Talk talk = dataList.get(i);
                        String[] strings = new String[]{talk.getName(), talk.getContent(), talk.getImg(), talk.getDates(), talk.getHead(), talk.getGender(), talk.getCollege()};
                        int[] ints = new int[]{talk.getId(), talk.getFine(), talk.getBad(), talk.getComment()};
                        Intent intent = new Intent(CampusTalk.this, Talk_more.class);
                        intent.putExtra("string", strings);
                        intent.putExtra("int", ints);
                        startActivity(intent);
                    });
                    head.setVisibility(View.GONE);
                    break;
                case 2:
                    if (showMore)
                        talkAdapter.notifyDataSetChanged();
                    loadComplete();//刷新结束
                    showBottom_line();
                    break;

            }
        }
    }

}
